package io.grpc.examples.helloworld.Service.impl;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.util.JsonFormat;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.examples.helloworld.HelloServiceGrpc;
import io.grpc.examples.helloworld.HelloServiceProto;

import java.net.URLDecoder;

public class HelloClient {

    public static void main(String[] args) throws InvalidProtocolBufferException {
        String ip = "127.0.0.1";
        int port = 9999;

        //替换ip、port
        ManagedChannel channel= ManagedChannelBuilder
                .forAddress(ip, port)
                .usePlaintext() //使用纯文本类型
                .build();

        //HelloService替换成proto文件的Service名称
        HelloServiceGrpc.HelloServiceBlockingStub blockingStub = HelloServiceGrpc.newBlockingStub(channel);

        //HelloServiceProto替换成.proto文件的java_outer_classname类名，
        //HelloServiceProto.HelloRequest替换成.proto文件的入参
        HelloServiceProto.HelloResponse response = blockingStub.sayHello(HelloServiceProto.HelloRequest.newBuilder()
                .setName("hellotest")  //request赋值
                .build());
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        String json1 = gson.toJson(response);
        System.out.println("gson"+json1);


        String json=JsonFormat.printer().print(response.toBuilder());
        json = URLDecoder.decode(json);
        System.out.println(json);

        String str= response.getMessage();
        System.out.println("grpc客户端调用，返回："+str);
    }
}
